﻿using Blazored.LocalStorage;

namespace BlazorApp3.Client.Infrastructure.Services;

internal class CounterRepository : ICounterRepository
{
    private const string Key = "__Counter";

    private readonly ILocalStorageService _localStorageService;

    public CounterRepository(ILocalStorageService localStorageService)
    {
        _localStorageService = localStorageService;
    }

    public async Task<int> GetCurrentCounter()
    {
        var counterString = await _localStorageService.GetItemAsStringAsync(Key);
        if (string.IsNullOrWhiteSpace(counterString)) {
            return 0;
        } else {
            int ret;
            if (int.TryParse(counterString, out ret)) {
                return ret;
            } else {
                return 0;
            }
        }
    }

    public async Task SaveCounter(int? counter)
    {
        await _localStorageService.SetItemAsStringAsync(Key, counter.HasValue ? counter.ToString() : "");
    }
}